<template>
  <view class="container">
    <button type="primary" @click="takePhoto">拍照识别文字</button>

    <view v-if="imagePath" class="image-preview">
      <image :src="imagePath" mode="aspectFit"></image>
    </view>

    <view class="result-container">
      <text v-if="loading">识别中...</text>
      <text v-else>{{ recognizedText || '识别结果将显示在这里' }}</text>
    </view>
  </view>
</template>


<script>
// import {main} from "@/utils/bdocr";
import {toBase64} from "@/js_sdk/hy-base64/hy-base64";
import {main} from "@/utils/ocr";

export default {
  data() {
    return {
      apiKey: 'NCm840YS7MC0DasfNz995dzx',
      secretKey: '5W9i4hFHTpHd9InYeBPtQmFGvxuVkJFC',
      imagePath: '',
      recognizedText: '',
      loading: false,
      accessToken: '',
      accessTokenExpire: 0 // Token过期时间
    };
  },
  methods: {
    // 1. 拍照
    takePhoto() {
      uni.chooseImage({
        count: 1,
        sourceType: ['camera'],
        maxWidth: 1024,
        maxHeight: 1024,
        sizeType: ['compressed'],
        success: (res) => {
          this.imagePath = res.tempFilePaths[0]
          console.log('图片路径'+this.imagePath)

          toBase64(this.imagePath).then((data) => {
            return main(data); // 返回 Promise
          }).then((ocrResult) => {
            console.log(ocrResult); // 打印 OCR 结果
            this.recognizedText = ocrResult; // 更新识别结果
            this.loading = false; // 关闭加载状态
          }).catch((err) => {
            console.error('识别失败:', err);
            this.loading = false;
            uni.showToast({ title: '识别失败', icon: 'none' });
          });


        },
        fail: (err) => {
          console.error('拍照失败:', err);
          uni.showToast({title: '拍照失败', icon: 'none'});
        }
      });
    }

  }
}
</script>

<style>
.container {
  padding: 20rpx;
}

.image-preview {
  margin: 20rpx 0;
  width: 100%;
  height: 400rpx;
  border: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-preview image {
  width: 90%;
  height: 90%;
}

.result-container {
  margin-top: 30rpx;
  padding: 20rpx;
  min-height: 200rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
}
</style>